<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="(value) => emit('update:visible', value)"
    :title="dialogTitle"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
    >
      <!-- 预算表单 -->
      <template v-if="formType === 'budget'">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预算年度" prop="year">
              <el-select v-model="formData.year" placeholder="请选择年度" style="width: 100%">
                <el-option
                  v-for="year in yearOptions"
                  :key="year"
                  :label="year"
                  :value="year"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预算类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择类型" style="width: 100%">
                <el-option label="运营预算" value="operation" />
                <el-option label="维护预算" value="maintenance" />
                <el-option label="建设预算" value="construction" />
                <el-option label="应急预算" value="emergency" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="预算名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入预算名称" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预算总额" prop="totalAmount">
              <el-input-number
                v-model="formData.totalAmount"
                :min="0"
                :precision="2"
                placeholder="请输入预算总额"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预算状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="草稿" value="draft" />
                <el-option label="待审核" value="pending" />
                <el-option label="已批准" value="approved" />
                <el-option label="执行中" value="executing" />
                <el-option label="已完成" value="completed" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="预算说明" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入预算说明"
          />
        </el-form-item>
        
        <el-form-item label="预算明细" prop="details">
          <el-table :data="formData.details" border style="width: 100%">
            <el-table-column prop="item" label="预算项目" width="200">
              <template #default="{ row, $index }">
                <el-input v-model="row.item" placeholder="预算项目" />
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="预算金额" width="150">
              <template #default="{ row, $index }">
                <el-input-number
                  v-model="row.amount"
                  :min="0"
                  :precision="2"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column prop="description" label="说明">
              <template #default="{ row, $index }">
                <el-input v-model="row.description" placeholder="说明" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{ row, $index }">
                <el-button
                  size="small"
                  type="danger"
                  @click="removeDetail($index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button
            type="primary"
            size="small"
            style="margin-top: 10px"
            @click="addDetail"
          >
            添加明细
          </el-button>
        </el-form-item>
      </template>

      <!-- 收入表单 -->
      <template v-if="formType === 'income'">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收入日期" prop="date">
              <el-date-picker
                v-model="formData.date"
                type="date"
                placeholder="请选择收入日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收入类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择类型" style="width: 100%">
                <el-option label="水费收入" value="water_fee" />
                <el-option label="电费收入" value="electricity_fee" />
                <el-option label="政府补贴" value="government_subsidy" />
                <el-option label="其他收入" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收入来源" prop="source">
              <el-input v-model="formData.source" placeholder="请输入收入来源" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收入金额" prop="amount">
              <el-input-number
                v-model="formData.amount"
                :min="0"
                :precision="2"
                placeholder="请输入收入金额"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="收入说明" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入收入说明"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="操作人" prop="operator">
              <el-input v-model="formData.operator" placeholder="请输入操作人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票号码" prop="invoiceNumber">
              <el-input v-model="formData.invoiceNumber" placeholder="请输入发票号码" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="相关附件" prop="attachments">
          <el-upload
            v-model:file-list="formData.attachments"
            action="#"
            :auto-upload="false"
            multiple
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传jpg/png/pdf文件，且不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </template>

      <!-- 支出表单 -->
      <template v-if="formType === 'expense'">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支出日期" prop="date">
              <el-date-picker
                v-model="formData.date"
                type="date"
                placeholder="请选择支出日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支出类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择类型" style="width: 100%">
                <el-option label="人员工资" value="salary" />
                <el-option label="设备维护" value="maintenance" />
                <el-option label="材料采购" value="material" />
                <el-option label="水电费" value="utility" />
                <el-option label="其他支出" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="支出用途" prop="purpose">
          <el-input v-model="formData.purpose" placeholder="请输入支出用途" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支出金额" prop="amount">
              <el-input-number
                v-model="formData.amount"
                :min="0"
                :precision="2"
                placeholder="请输入支出金额"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预算科目" prop="budgetSubject">
              <el-select v-model="formData.budgetSubject" placeholder="请选择预算科目" style="width: 100%">
                <el-option label="运营费用" value="operation" />
                <el-option label="维护费用" value="maintenance" />
                <el-option label="人员费用" value="personnel" />
                <el-option label="设备费用" value="equipment" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="支出说明" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入支出说明"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请人" prop="applicant">
              <el-input v-model="formData.applicant" placeholder="请输入申请人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批状态" prop="approvalStatus">
              <el-select v-model="formData.approvalStatus" placeholder="请选择状态" style="width: 100%">
                <el-option label="待审批" value="pending" />
                <el-option label="已审批" value="approved" />
                <el-option label="已拒绝" value="rejected" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="支出凭证" prop="vouchers">
          <el-upload
            v-model:file-list="formData.vouchers"
            action="#"
            :auto-upload="false"
            multiple
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传jpg/png/pdf文件，且不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// Props
interface Props {
  modelValue: boolean
  fundData?: any
  dialogType: 'add' | 'edit'
  formType: 'budget' | 'income' | 'expense'
}

const props = withDefaults(defineProps<Props>(), {
  fundData: null,
  dialogType: 'add',
  formType: 'budget'
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  confirm: []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const loading = ref(false)
const yearOptions = ref([2024, 2023, 2022, 2021, 2020])

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const dialogTitle = computed(() => {
  const typeMap = {
    budget: '预算',
    income: '收入',
    expense: '支出'
  }
  const actionMap = {
    add: '新增',
    edit: '编辑'
  }
  return `${actionMap[props.dialogType]}${typeMap[props.formType]}`
})

// 表单数据
const formData = reactive({
  // 通用字段
  id: null,
  type: '',
  amount: null,
  description: '',
  
  // 预算字段
  year: new Date().getFullYear(),
  name: '',
  totalAmount: null,
  status: 'draft',
  details: [],
  
  // 收入字段
  date: '',
  source: '',
  operator: '',
  invoiceNumber: '',
  attachments: [],
  
  // 支出字段
  purpose: '',
  budgetSubject: '',
  applicant: '',
  approvalStatus: 'pending',
  vouchers: []
})

// 表单验证规则
const formRules = computed<FormRules>(() => {
  const commonRules = {
    type: [{ required: true, message: '请选择类型', trigger: 'change' }],
    amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
    description: [{ required: true, message: '请输入说明', trigger: 'blur' }]
  }

  if (props.formType === 'budget') {
    return {
      ...commonRules,
      year: [{ required: true, message: '请选择年度', trigger: 'change' }],
      name: [{ required: true, message: '请输入预算名称', trigger: 'blur' }],
      totalAmount: [{ required: true, message: '请输入预算总额', trigger: 'blur' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    }
  } else if (props.formType === 'income') {
    return {
      ...commonRules,
      date: [{ required: true, message: '请选择收入日期', trigger: 'change' }],
      source: [{ required: true, message: '请输入收入来源', trigger: 'blur' }],
      operator: [{ required: true, message: '请输入操作人', trigger: 'blur' }]
    }
  } else {
    return {
      ...commonRules,
      date: [{ required: true, message: '请选择支出日期', trigger: 'change' }],
      purpose: [{ required: true, message: '请输入支出用途', trigger: 'blur' }],
      budgetSubject: [{ required: true, message: '请选择预算科目', trigger: 'change' }],
      applicant: [{ required: true, message: '请输入申请人', trigger: 'blur' }],
      approvalStatus: [{ required: true, message: '请选择审批状态', trigger: 'change' }]
    }
  }
})

// 监听数据变化
watch(() => props.fundData, (newData) => {
  if (newData && props.dialogType === 'edit') {
    Object.assign(formData, newData)
  }
}, { immediate: true })

watch(() => props.modelValue, (newValue) => {
  if (newValue && props.dialogType === 'add') {
    resetForm()
  }
})

// 方法
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    type: '',
    amount: null,
    description: '',
    year: new Date().getFullYear(),
    name: '',
    totalAmount: null,
    status: 'draft',
    details: [],
    date: '',
    source: '',
    operator: '',
    invoiceNumber: '',
    attachments: [],
    purpose: '',
    budgetSubject: '',
    applicant: '',
    approvalStatus: 'pending',
    vouchers: []
  })
  
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

const addDetail = () => {
  formData.details.push({
    item: '',
    amount: null,
    description: ''
  })
}

const removeDetail = (index: number) => {
  formData.details.splice(index, 1)
}

const handleClose = () => {
  visible.value = false
}

const handleConfirm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('操作成功')
    emit('confirm')
    visible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 600;
}

:deep(.el-upload__tip) {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

:deep(.el-table) {
  margin-bottom: 10px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>